<template>
  <div class="question-analytics">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <i class="el-icon-document"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalQuestions }}</div>
              <div class="stat-label">题目总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon avg-icon">
              <i class="el-icon-s-data"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.avgCorrectRate }}%</div>
              <div class="stat-label">平均正确率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon high-icon">
              <i class="el-icon-top"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.highErrorRateCount }}</div>
              <div class="stat-label">高错误率题目</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon low-icon">
              <i class="el-icon-bottom"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.lowErrorRateCount }}</div>
              <div class="stat-label">低错误率题目</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 题目正确率分布 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>题目正确率分布</span>
          </div>
          <div class="chart-container">
            <div ref="correctRateChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 分类正确率排行 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>分类正确率排行</span>
          </div>
          <div class="chart-container">
            <div ref="categoryChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 高错误率题目列表 -->
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>高错误率题目列表（需要优化）</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="exportHighErrorQuestions">
              导出列表
            </el-button>
          </div>
          
          <!-- 筛选条件 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="4">
              <el-select v-model="filterCategory" placeholder="选择分类" clearable>
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="filterType" placeholder="选择题型" clearable>
                <el-option label="选择题" value="choice"></el-option>
                <el-option label="判断题" value="judge"></el-option>
                <el-option label="填空题" value="fill"></el-option>
                <el-option label="代码题" value="code"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="filterErrorRate" placeholder="错误率范围" clearable>
                <el-option label=">80%" value="80"></el-option>
                <el-option label=">60%" value="60"></el-option>
                <el-option label=">40%" value="40"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleFilter">筛选</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-col>
          </el-row>

          <el-table :data="filteredHighErrorQuestions" border style="width: 100%">
            <el-table-column prop="title" label="题目" width="300">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.title" placement="top">
                  <span>{{ scope.row.title.length > 40 ? scope.row.title.substring(0, 40) + '...' : scope.row.title }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column prop="type" label="题型" width="80" align="center">
              <template slot-scope="scope">
                <el-tag :type="getTypeTagType(scope.row.type)">{{ getTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="difficulty" label="难度" width="80" align="center">
              <template slot-scope="scope">
                <el-tag :type="getDifficultyTagType(scope.row.difficulty)">{{ getDifficultyText(scope.row.difficulty) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="correctRate" label="正确率" width="100" align="center">
              <template slot-scope="scope">
                <span style="color: #F56C6C; font-weight: bold;">{{ scope.row.correctRate }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="attemptCount" label="答题次数" width="100" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="handleViewQuestion(scope.row)">查看</el-button>
                <el-button size="mini" type="warning" @click="handleOptimize(scope.row)">优化</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 20px; text-align: right;"
          ></el-pagination>
        </el-card>
      </el-col>
    </el-row>

    <!-- 题目详情对话框 -->
    <el-dialog title="题目详情" :visible.sync="questionDetailVisible" width="800px">
      <div v-if="selectedQuestion" class="question-detail">
        <h3>{{ selectedQuestion.title }}</h3>
        <p><strong>分类：</strong>{{ selectedQuestion.category }}</p>
        <p><strong>题型：</strong>{{ getTypeText(selectedQuestion.type) }}</p>
        <p><strong>难度：</strong>{{ getDifficultyText(selectedQuestion.difficulty) }}</p>
        <p><strong>正确率：</strong><span style="color: #F56C6C;">{{ selectedQuestion.correctRate }}%</span></p>
        <p><strong>答题次数：</strong>{{ selectedQuestion.attemptCount }}</p>
        
        <div v-if="selectedQuestion.type === 'choice'">
          <p><strong>选项：</strong></p>
          <p>A. {{ selectedQuestion.optionA }}</p>
          <p>B. {{ selectedQuestion.optionB }}</p>
          <p>C. {{ selectedQuestion.optionC }}</p>
          <p>D. {{ selectedQuestion.optionD }}</p>
          <p><strong>正确答案：</strong>{{ selectedQuestion.correctAnswer }}</p>
        </div>
        
        <div v-if="selectedQuestion.type === 'judge'">
          <p><strong>正确答案：</strong>{{ selectedQuestion.correctAnswer === 'true' ? '正确' : '错误' }}</p>
        </div>
        
        <div v-if="selectedQuestion.type === 'fill'">
          <p><strong>正确答案：</strong>{{ selectedQuestion.correctAnswer }}</p>
        </div>
        
        <div v-if="selectedQuestion.explanation">
          <p><strong>解析：</strong>{{ selectedQuestion.explanation }}</p>
        </div>
        
        <div class="error-analysis">
          <h4>错误分析</h4>
          <p><strong>常见错误答案：</strong></p>
          <ul>
            <li v-for="(error, index) in selectedQuestion.commonErrors" :key="index">
              {{ error.answer }} ({{ error.count }}次，{{ error.percentage }}%)
            </li>
          </ul>
        </div>
      </div>
    </el-dialog>

    <!-- 题目优化对话框 -->
    <el-dialog title="题目优化建议" :visible.sync="optimizeDialogVisible" width="600px">
      <div v-if="selectedQuestion" class="optimize-suggestions">
        <h4>优化建议</h4>
        <el-alert
          title="题目难度过高"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;"
        >
          <p>该题目的正确率较低，建议：</p>
          <ul>
            <li>检查题目表述是否清晰</li>
            <li>考虑降低题目难度</li>
            <li>优化选项设置</li>
            <li>完善题目解析</li>
          </ul>
        </el-alert>
        
        <el-form label-width="100px">
          <el-form-item label="优化建议">
            <el-input
              type="textarea"
              v-model="optimizeSuggestion"
              placeholder="请输入具体的优化建议"
              :rows="4"
            ></el-input>
          </el-form-item>
          <el-form-item label="优先级">
            <el-radio-group v-model="optimizePriority">
              <el-radio label="high">高</el-radio>
              <el-radio label="medium">中</el-radio>
              <el-radio label="low">低</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="optimizeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleOptimizeSubmit">提交建议</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'QuestionAnalytics',
  data() {
    return {
      stats: {
        totalQuestions: 1250,
        avgCorrectRate: 78.5,
        highErrorRateCount: 45,
        lowErrorRateCount: 320
      },
      filterCategory: '',
      filterType: '',
      filterErrorRate: '',
      categoryOptions: [
        { id: 1, name: '前端开发' },
        { id: 2, name: '后端开发' },
        { id: 3, name: '数据库' },
        { id: 4, name: 'JavaScript' },
        { id: 5, name: 'Vue.js' }
      ],
      highErrorQuestions: [
        {
          id: 1,
          title: 'Vue.js 中 computed 和 watch 的区别是什么？',
          category: '前端开发 > Vue.js',
          type: 'choice',
          difficulty: 'hard',
          correctRate: 35,
          attemptCount: 150,
          createTime: '2024-01-10 10:00:00',
          optionA: 'computed 是计算属性，watch 是监听器',
          optionB: 'computed 有缓存，watch 没有缓存',
          optionC: 'computed 是同步的，watch 是异步的',
          optionD: '以上都是',
          correctAnswer: 'D',
          explanation: 'computed 和 watch 在 Vue.js 中有不同的用途和特点。',
          commonErrors: [
            { answer: 'A', count: 45, percentage: 30 },
            { answer: 'B', count: 30, percentage: 20 },
            { answer: 'C', count: 15, percentage: 10 }
          ]
        },
        {
          id: 2,
          title: 'JavaScript 中 Promise 的 then 方法返回什么？',
          category: '前端开发 > JavaScript',
          type: 'choice',
          difficulty: 'medium',
          correctRate: 42,
          attemptCount: 200,
          createTime: '2024-01-08 14:30:00',
          optionA: 'undefined',
          optionB: '一个新的 Promise',
          optionC: '原始值',
          optionD: '错误对象',
          correctAnswer: 'B',
          explanation: 'Promise 的 then 方法返回一个新的 Promise 对象。',
          commonErrors: [
            { answer: 'A', count: 60, percentage: 30 },
            { answer: 'C', count: 40, percentage: 20 },
            { answer: 'D', count: 20, percentage: 10 }
          ]
        },
        {
          id: 3,
          title: 'MySQL 中索引失效的情况有哪些？',
          category: '数据库 > MySQL',
          type: 'choice',
          difficulty: 'hard',
          correctRate: 28,
          attemptCount: 120,
          createTime: '2024-01-05 09:15:00',
          optionA: '使用 != 或 <> 操作符',
          optionB: '使用 LIKE 以 % 开头',
          optionC: '使用 OR 连接条件',
          optionD: '以上都是',
          correctAnswer: 'D',
          explanation: '这些情况都可能导致 MySQL 索引失效。',
          commonErrors: [
            { answer: 'A', count: 35, percentage: 29 },
            { answer: 'B', count: 25, percentage: 21 },
            { answer: 'C', count: 20, percentage: 17 }
          ]
        }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      questionDetailVisible: false,
      selectedQuestion: null,
      optimizeDialogVisible: false,
      optimizeSuggestion: '',
      optimizePriority: 'medium'
    }
  },
  computed: {
    filteredHighErrorQuestions() {
      let result = this.highErrorQuestions;
      
      if (this.filterCategory) {
        result = result.filter(q => 
          q.category.includes(this.getCategoryName(this.filterCategory))
        );
      }
      
      if (this.filterType) {
        result = result.filter(q => q.type === this.filterType);
      }
      
      if (this.filterErrorRate) {
        const rate = parseInt(this.filterErrorRate);
        result = result.filter(q => q.correctRate <= (100 - rate));
      }
      
      return result;
    }
  },
  watch: {
    filteredHighErrorQuestions: {
      handler(newVal) {
        this.total = newVal.length;
      },
      immediate: true
    }
  },
  mounted() {
    this.initCharts();
  },
  methods: {
    getTypeTagType(type) {
      const typeMap = {
        choice: 'primary',
        judge: 'success',
        fill: 'warning',
        code: 'danger'
      };
      return typeMap[type] || 'info';
    },
    getTypeText(type) {
      const typeMap = {
        choice: '选择题',
        judge: '判断题',
        fill: '填空题',
        code: '代码题'
      };
      return typeMap[type] || type;
    },
    getDifficultyTagType(difficulty) {
      const difficultyMap = {
        easy: 'success',
        medium: 'warning',
        hard: 'danger'
      };
      return difficultyMap[difficulty] || 'info';
    },
    getDifficultyText(difficulty) {
      const difficultyMap = {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      };
      return difficultyMap[difficulty] || difficulty;
    },
    getCategoryName(id) {
      const category = this.categoryOptions.find(c => c.id === id);
      return category ? category.name : '';
    },
    handleFilter() {
      // 筛选逻辑已在 computed 中处理
    },
    resetFilter() {
      this.filterCategory = '';
      this.filterType = '';
      this.filterErrorRate = '';
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleViewQuestion(row) {
      this.selectedQuestion = row;
      this.questionDetailVisible = true;
    },
    handleOptimize(row) {
      this.selectedQuestion = row;
      this.optimizeSuggestion = '';
      this.optimizePriority = 'medium';
      this.optimizeDialogVisible = true;
    },
    handleOptimizeSubmit() {
      // 这里应该调用提交优化建议API
      this.$message.success('优化建议提交成功');
      this.optimizeDialogVisible = false;
    },
    exportHighErrorQuestions() {
      // 这里应该导出高错误率题目列表
      this.$message.success('导出成功');
    },
    initCharts() {
      // 这里可以集成 ECharts 来显示图表
      console.log('初始化图表');
    }
  }
}
</script>

<style scoped>
.question-analytics {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.total-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.avg-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.high-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.low-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  border-radius: 4px;
}

.question-detail h3 {
  margin-bottom: 15px;
  color: #303133;
}

.question-detail p {
  margin: 8px 0;
  color: #606266;
}

.error-analysis {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.error-analysis h4 {
  margin-bottom: 10px;
  color: #303133;
}

.error-analysis ul {
  margin: 0;
  padding-left: 20px;
}

.error-analysis li {
  margin: 5px 0;
  color: #606266;
}

.optimize-suggestions h4 {
  margin-bottom: 15px;
  color: #303133;
}
</style>
